<?php
/**
 * Created by PhpStorm.
 * User: ycbwl
 * Date: 2018/12/9
 * Time: 3:00 PM
 */
namespace app\api\service;

use Aes\WXBizDataCrypt;
use app\lib\exception\ApiException;
use app\lib\exception\ErrorCode;

class User{

    /**
     * @return mixed
     * 小程序登录
     */
    public static function miniLogin(){
        if(input("post.code")){
            $miniUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=".config("wx.app_id")."&secret=".config("wx.app_secret")."&js_code=".input("post.code")."&grant_type=authorization_code";
            $result = curl($miniUrl,'','GET');
            $wxResult = json_decode($result,true);
            if(empty($wxResult)){
                throw new ApiException(ErrorCode::$E40002);
            }else{
                $loginFail = array_key_exists('errcode',$wxResult);
                if($loginFail){
                    throw new ApiException(ErrorCode::$E40002);
                }else{
                    $appid = config("wx.app_id");
                    $sessionKey = $wxResult['session_key'];
                    $encryptedData=input("post.encryptedData");
                    $iv = input("post.iv");
                    $pc = new WXBizDataCrypt($appid, $sessionKey);
                    $errCode = $pc->decryptData($encryptedData, $iv, $data );
                    if($errCode == 0) {
                        $wxData = json_decode($data,true);
                        $userInfoModel = new \app\api\model\User();
                        $data = $userInfoModel->where("openid",$wxData['openId'])->find();
                        if(!empty($data)){
                            $userModel = \app\api\model\User::find($data['id']);
                            $userModel->openid = $wxData['openId'];
                            $userModel->nickname = preg_replace('/[\x{10000}-\x{10FFFF}]/u', '', $wxData['nickName']);
                            $userModel->save();
                            $uid = $userModel->id;
                        }else{
                            $userModel = new \app\api\model\User();
                            $userModel->openid = $wxData['openId'];
                            $userModel->nickname = preg_replace('/[\x{10000}-\x{10FFFF}]/u', '', $wxData['nickName']);
                            $userModel->save();
                            $uid = $userModel->id;
                        }
                        $userInfo = \app\api\model\User::find($uid);
                        if(!$userInfo){
                            throw new ApiException(ErrorCode::$E40003,'登录失败！');
                        }
                        $token = \app\lib\Token::cacheToken($userInfo,'mini');
                        return ajaxReturn(1,'',$token);
                    } else {
                        throw new ApiException(ErrorCode::$E40003,'登录失败！');
                    }
                }
            }
        }else{
            throw new ApiException(ErrorCode::$E40003,'code码无效！');
        }
    }

}